#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/3/19 17:18
# @Author  : huidong.bai
# @File    : conftest.py
# @Software: PyCharm
# @Mail    : MasterBai2018@outlook.com

import pdb
import allure
from loguru import logger
from Run_Mongo import cmder
from src.utils.common import uuid
from _pytest.python import Metafunc
# mongo日志
logging = logger.opt()
logger.remove()
from src.utils.MangoDownload import Download, FileType
from src.core.TestCaseParser import TestCaseParser
from src.core.Routine.RoutineTextFileParser import RoutineTextFileParser
from src.core.Ability.CpuMemAbilityFixture import *
from src.core.Ability.DelayFixture import *
from src.core.Ability.FAFRFixture import *


def pytest_addoption(parser):
    parser.addoption(
        "--mongo_suite_id",
        action="store",
        type=str,
        help="The testsuite id for each suite.",
    )
    parser.addoption(
        "--mongo_suite_tag",
        action="store",
        type=str,
        help="The tags for each suite runtime.",
    )
    parser.addoption(
        "--mongo_suite_name",
        action="store",
        type=str,
        help="The name for running suite.",
    )
    parser.addoption(
        "--mongo_config",
        action="store",
        type=str,
        help="The config file for aibs-sdk.",
    )
    parser.addoption(
        "--mongo_case_list",
        action="store",
        type=str,
        help="The testcase list for each suite.",
    )
    parser.addoption(
        "--mongo_scenario_config",
        action="store",
        type=str,
        help="The config file for scene.",
    )
    parser.addoption(
        "--mongo_report",
        action="store",
        type=str,
        help="The test report file for each suite.",
    )
    parser.addoption(
        "--mongo_root_dir",
        action="store",
        type=str,
        help="The root path when running.",
    )
    parser.addoption(
        "--mongo_workspace",
        action="store",
        type=str,
        help="The workspace for suite when running.",
    )
    parser.addoption(
        "--mongo_solution_space",
        action="store",
        type=str,
        help="The solution path in workspace when suite is running.",
    )
    parser.addoption(
        "--mongo_filter_case_line",
        action="store",
        type=str,
        default=None,
        help="The case list filter for suite.",
    )
    parser.addoption(
        "--mongo_suite_abstract",
        action="store",
        type=str,
        default=None,
        help="The case list filter for suite.",
    )
    parser.addoption(
        "--mongo_detail",
        action="store",
        type=str,
        default="False",
        help="The case list filter for suite.",
    )
    parser.addoption(
        "--gdb_mode",
        action="store",
        type=str,
        default="False",
        help="The case list filter for suite.",
    )
    parser.addoption(
        "--mongo_ftp_downloader",
        action="store",
        type=int,
        default=None,
        help="The ftp downloader mode.",
    )
    parser.addoption(
        "--mongo_log_save_option",
        action="store",
        type=str,
        default=None,
        help="The log save option.",
    )
    parser.addoption(
        "--mongo_check_project",
        action="store",
        type=str,
        default=None,
        help="is choice for check_bev.",
    )


def pytest_configure(config):
    cmder.suite_id = config.getoption("--mongo_suite_id")
    cmder.suite_name = config.getoption("--mongo_suite_name")
    cmder.suite_tag = config.getoption("--mongo_suite_tag")
    cmder.config = config.getoption("--mongo_config")
    cmder.case_list = config.getoption("--mongo_case_list")
    cmder.report = config.getoption("--mongo_report")
    cmder.root_dir = config.getoption("--mongo_root_dir")
    cmder.workspace = config.getoption("--mongo_workspace")
    cmder.solution_space = config.getoption("--mongo_solution_space")
    cmder.filter_case_line = config.getoption("--mongo_filter_case_line")
    cmder.suite_abstract = config.getoption("--mongo_suite_abstract")
    cmder.detail = config.getoption("--mongo_detail")
    cmder.gdb = config.getoption("--gdb_mode")
    cmder.ftp_downer = config.getoption("--mongo_ftp_downloader")
    cmder.log_save_option = config.getoption("--mongo_log_save_option")
    cmder.source_lcs_config = config.getoption("--mongo_scenario_config")
    cmder.project = config.getoption("--mongo_check_project")

    # 创建suite文件夹
    cmder.suite_dir = os.path.join(cmder.workspace, cmder.suite_id)
    if not os.path.exists(cmder.suite_dir):
        os.makedirs(cmder.suite_dir)

    # 日志写入文件
    log_format = "{time:YYYY-MM-DD HH:mm:ss} | {level}| {name}:{module}:{line:4} | {message}"
    logging.add(sink=open(f'{cmder.suite_dir}/mongo.log', 'w', encoding='UTF-8'), format=log_format, enqueue=True)

    if not cmder.config:
        pytest.skip(f"Error {cmder.config} config file, skip the test suite.")

    # 解析Case文件
    try:
        if cmder.suite_name == "ROUTINE":
            reader = RoutineTextFileParser(file_path=cmder.case_list)
            run_case_list = reader.get_case_filter(cmder.filter_case_line)
            cmder.run_case_list = run_case_list
            cmder.case_nums = len(run_case_list)
        else:
            reader = TestCaseParser(case_path=cmder.case_list)
            run_case_list = reader.get_case_list(cmder.filter_case_line)
            cmder.run_case_list = run_case_list
            cmder.case_header = TestCaseParser.case_header
            cmder.case_nums = len(run_case_list)
    except Exception as e:
        raise Exception(f"Mongo running error: {e}, caselist: {cmder.case_list}")

    # 自动下载CaseList的音频资源资源
    if cmder.ftp_downer == 0 or cmder.ftp_downer == 1:
        downloader = Download()
        downloader.start_download(cmder.case_list, FileType.FILE_TYPE_CASE_LIST)


def pytest_generate_tests(metafunc: Metafunc):
    case_list = cmder.run_case_list
    metafunc.parametrize("testcase", case_list)


def pytest_collection_modifyitems(items: list):
    for item in items:
        item.name = item.name.encode("utf-8").decode()
        item._nodeid = item.nodeid.encode("utf-8").decode() + uuid()
        if cmder.case_header.faPassRate.value or cmder.case_header.frPassRate.value:
            item.fixturenames.append("ASRFARateCalculation")
            item.fixturenames.append("ASRPasrResultFixture")
        if cmder.case_header.delayTolerance.value:
            item.fixturenames.append("RecordDelayFixture")
            item.fixturenames.append("AnalysisDelayFixture")
        if cmder.case_header.cpuMemTag.value:
            item.fixturenames.append("CpuMemCalculate")
